<?php
/**
 * Created by PhpStorm.
 * User: 764432054@qq.com
 * Date: 2018/7/29
 * Time: 11:28
 * pcntl_waitpid()
 * 返回退出的子进程进程号，发生错误时返回-1,如果提供了 WNOHANG作为option（wait3可用的系统）并且没有可用子进程时返回0
 */
$pid=pcntl_fork();
if($pid<0)exit("fork error ".PHP_EOL);
if($pid>0){
    cli_set_process_title("php_parent_".posix_getpid());
    echo "parent1:".posix_getpid().PHP_EOL;
    $wait_res=0;
    pcntl_signal(SIGCHLD,function() use($pid,&$wait_res){
        echo "收到".$pid."子进程退出".PHP_EOL;
        $wait_res=pcntl_waitpid($pid,$status,WNOHANG);
        echo "wait_Res=".var_export($wait_res,true)."--status=".var_export($status,true).PHP_EOL;
    });
    /*while(true){
        sleep(6);
        $r=pcntl_signal_dispatch();
        echo $r."--".$i."--".$wait_res.PHP_EOL;
        if($wait_res!=0){
            break;
        }
        $i++;
    }*/
    echo "parent2:".posix_getpid().PHP_EOL;
    //sleep(20);
    for($i=0;$i<20;$i++){
        echo "parent_".$i.PHP_EOL;
        sleep(1);
    }
    echo "parent3:".posix_getpid().PHP_EOL;
    echo "parent_exit".PHP_EOL;
}else{
    cli_set_process_title("php_son_".posix_getpid());
    for($i=0;$i<10;$i++){
        echo "son_".$i.PHP_EOL;
        sleep(1);
    }
    echo "son_exit".PHP_EOL;
    exit;
}


